//
//  CreditCardViewController.m
//  Rich
//
//  Created by Kenny Chen on 13/9/25.
//  Copyright (c) 2013年 Kenny Chen. All rights reserved.
//
// TODO: Handle APR
//

#import "CreditCardViewController.h"

@interface CreditCardViewController ()

@end

@implementation CreditCardViewController

@synthesize creditCardBill;

- (void)initDueDatePicker
{
    dueDatePicker = [[FormatableDatePicker alloc] init];
    dueDatePicker.date = [NSDate date];
}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        self.title = RichLocaleString(@"Credit Card");
        creditCardBill = nil;
        
        [self initDatePicker];
        [self initDueDatePicker];
        [self initInputToolbar:RichInputToolbarButtonNext | RichInputToolbarButtonDone];
        
        accountPicker = [[AccountViewController alloc] initWithStyle:UITableViewStylePlain];
        accountPicker.mode = RichTableModeListReadonly;
        accountPicker.loadType = AccountTypeCreditCards;
        accountPicker.callerDelegate = self;
        
        transPicker = [[RichTransactionPicker alloc] initWithStyle:UITableViewStylePlain];
        transPicker.tableView.tag |= TransPickerMinorTag;
        transPicker.mode = RichTableModeListReadonly;
        //transPicker.callerDelegate = self;
        
        paymentPicker = [[RichTransactionPicker alloc] initWithStyle:UITableViewStylePlain];
        paymentPicker.tableView.tag |= PaymentPickerMinorTag;
        paymentPicker.mode = RichTableModeListEditable; // TODO
        //paymentPicker.callerDelegate = self;
    }
    
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    //self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    /* Load picked transactions/payments to picker for update mode */
    if (self.mode == RichTableModeUpdate)
        [self reloadPickers];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if (self.mode != RichTableModeUpdate)
        [[RichDelegate core] loadCreditCardBills];
    
    if (self.mode == RichTableModeListReadonly && [self tableView:self.tableView numberOfRowsInSection:2] > 0)
        self.navigationItem.rightBarButtonItem = self.editButtonItem;
    else
        self.navigationItem.rightBarButtonItem = nil;
    
    /* If we return from update tableComponents, reload pickers */
    if (creditCardBill == nil)
        [self reloadPickers];
    
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#if 0
- (void)setCreditCardBill:(RichCreditCardBill *)bill
{
    creditCardBill.billId = bill.billId;
    creditCardBill.accountId = bill.accountId;
    creditCardBill.closingDate = bill.closingDate;
    creditCardBill.dueDate = bill.dueDate;
    [creditCardBill.transactions removeAllObjects];
    [creditCardBill.transactions addObjectsFromArray:bill.transactions];
    [creditCardBill.payments removeAllObjects];
    [creditCardBill.payments addObjectsFromArray:bill.payments];
}
#endif

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [super numberOfSectionsInTableView:tableView];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0)
        return 5;
    else if (section == 1)
        return 1;
    else
        return [[[[RichDelegate core] creditCardBills] allKeys] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    RichTableViewTextfieldCell *textfieldCell = nil;
    
    if ([indexPath section] == 0) {
        if ([indexPath row] != 3) {
            tableCellStyle = RichTableCellStyleTextfield;
            textfieldCell = (RichTableViewTextfieldCell *)[super tableView:tableView cellForRowAtIndexPath:indexPath];
            
            cell = textfieldCell;
        }
        
        switch ([indexPath row]) {
            case 0:
                textfieldCell.textLabel.text = RichLocaleString(@"Credit Card Account");
                textfieldCell.textfield.returnKeyType = UIReturnKeyNext;
                textfieldCell.textfield.inputView = accountPicker.view;
                textfieldCell.textfield.text = [[[RichDelegate core] accounts:accounts findAccountByID:creditCardBill.accountId] name];
                break;
                
            case 1:
                textfieldCell.textLabel.text = RichLocaleString(@"Closing Date");
                textfieldCell.textfield.returnKeyType = UIReturnKeyNext;
                textfieldCell.textfield.inputView = datePicker;
                textfieldCell.textfield.text = [[RichDelegate core] stringFromDate:creditCardBill.closingDate format:@"yyyy-MM-dd"];
                break;
            
            case 2:
                textfieldCell.textLabel.text = RichLocaleString(@"Due Date");
                textfieldCell.textfield.returnKeyType = UIReturnKeyDone;
                textfieldCell.textfield.inputView = dueDatePicker;
                textfieldCell.textfield.text = [[RichDelegate core] stringFromDate:creditCardBill.dueDate format:@"yyyy-MM-dd"];
                break;

            case 3:
                tableCellStyle = RichTableCellStyleDefault;
                cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
                cell.textLabel.text = RichLocaleString(@"New Balance");
                cell.selectionStyle = UITableViewCellSelectionStyleBlue;
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                cell.detailTextLabel.text = [NSString stringWithFormat:@"$ %ld", [[RichDelegate core] totalAmountOfTransactions:transPicker.pickedTransArray]];
                
                break;
            
            case 4:
                tableCellStyle = RichTableCellStyleDefault;
                cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
                cell.textLabel.text = RichLocaleString(@"Payment");
                cell.selectionStyle = UITableViewCellSelectionStyleBlue;
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                cell.detailTextLabel.text = [NSString stringWithFormat:@"$ %ld", [[RichDelegate core] totalAmountOfPayments:paymentPicker.pickedTransArray]];
                
                break;
        }
    }
    else if ([indexPath section] == 1) {
        tableCellStyle = RichTableCellStyleButton;
        cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
        if (self.mode == RichTableModeUpdate)
            cell.textLabel.text = RichLocaleString(@"Save");
        else
            cell.textLabel.text = RichLocaleString(@"New Bill");
    }
    else if ([indexPath section] == 2) {
        tableCellStyle = RichTableCellStyleValue;
        cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
        
        NSNumber *billId = [[[[RichDelegate core] creditCardBills] allKeys] objectAtIndex:[indexPath row]];
        RichCreditCardBill *bill = [[[RichDelegate core] creditCardBills] objectForKey:billId];
        
        if (bill) {
            /* Load transactions associated to this bill for calculating new balance */
            [[RichDelegate core] creditCardBill:bill loadAssociatedTransactionsToArray:bill.transactions database:nil];
            cell.textLabel.text = [NSString stringWithFormat:@"%@", [[RichDelegate core] stringFromDate:bill.closingDate format:@"YYYY-MM-dd"]];
            cell.detailTextLabel.text = [NSString stringWithFormat:RichLocaleString(@"$ %d"), bill.newBalance];
        }
        
        if ([[[[RichDelegate core] creditCardBills] allKeys] count] > 0)
            self.navigationItem.rightBarButtonItem = self.editButtonItem;
        else {
            self.navigationItem.rightBarButtonItem = nil;
            [self setEditing:NO];
        }
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSNumber *billId = [[[[RichDelegate core] creditCardBills] allKeys] objectAtIndex:[indexPath row]];
        RichCreditCardBill *bill = [[[RichDelegate core] creditCardBills] objectForKey:billId];
        
        [[RichDelegate core] deleteCreditCardBill:bill];
        
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        
        /* Reload transaction/payment pickers if any bill is deleted (some transactions/payments are disassociated) */
        [self reloadPickers];
        
        if ([[[[RichDelegate core] creditCardBills] allKeys] count] > 0)
            self.navigationItem.rightBarButtonItem = self.editButtonItem;
        else {
            self.navigationItem.rightBarButtonItem = nil;
            [self setEditing:NO];
        }
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.editing)
        return UITableViewCellEditingStyleDelete;
    else
        return UITableViewCellEditingStyleNone;
}

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a story board-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}

 */

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == RichTableViewTagAccount) {
        /*
         * Called by AccountViewController
         */
        currentTextfield.text = accountPicker.account.name;
    }
#if 0
    else if (tableView.tag == (RichTableViewTagTransPicker | TransPickerMinorTag)) {
        /*
         * Called by transPicker
         */
        [creditCardBill.transactions removeAllObjects];
        
        for (RichTransactionGeneral *__trans in transPicker.pickedTransArray)
            [creditCardBill.transactions addObject:__trans];
    }
    else if (tableView.tag == (RichTableViewTagTransPicker | PaymentPickerMinorTag)) {
        /*
         * Called by paymentPicker
         */
        [creditCardBill.payments removeAllObjects];
        
        for (RichTransactionGeneral *__payment in paymentPicker.pickedTransArray)
            [creditCardBill.payments addObject:__payment];
    }
#endif
    else {
        /*
         * Called by self
         */
        
        if ([indexPath section] == 0 && [indexPath row] == 3) {
            transPicker.navigator = self.navigator;
            [self.navigator pushViewController:transPicker animated:YES];
        }
        else if ([indexPath section] == 0 && [indexPath row] == 4) {
            /* Clear previous selected payments first if any */
            //[creditCardBill.payments removeAllObjects];
            
            paymentPicker.navigator = self.navigator;
            [self.navigator pushViewController:paymentPicker animated:YES];
        }
        else if ([indexPath section] == 1) {
            if (self.mode == RichTableModeUpdate) {
                NSMutableArray *__transToDisassoc = [[NSMutableArray alloc] init];
                
                /* find out transactions to be disassociated */
                for (RichTransactionGeneral *__curr_trans in creditCardBill.transactions) {
                    BOOL picked = NO;
                    
                    for (RichTransactionGeneral *__picked_trans in transPicker.pickedTransArray) {
                        if (__curr_trans.transId == __picked_trans.transId) {
                            picked = YES;
                            break;
                        }
                    }
                    
                    if (!picked)
                        [__transToDisassoc addObject:__curr_trans];
                }
                
                /* find out payments to be disassociated */
                for (RichTransactionGeneral *__curr_payment in creditCardBill.payments) {
                    BOOL picked = NO;
                    
                    for (RichTransactionGeneral *__picked_payment in paymentPicker.pickedTransArray) {
                        if (__curr_payment.transId == __picked_payment.transId) {
                            picked = YES;
                            break;
                        }
                    }
                    
                    if (!picked)
                        [__transToDisassoc addObject:__curr_payment];
                }
                
                /* Disassociate old transactions/payments in bill */
                [[RichDelegate core] creditCardBill:creditCardBill disassociateTransactionsFromArray:__transToDisassoc database:nil];
                
                [__transToDisassoc removeAllObjects];
                [__transToDisassoc release];
                
                /* Reload picked transactions/payments in bill */
                creditCardBill.transactions = transPicker.pickedTransArray;
                creditCardBill.payments = paymentPicker.pickedTransArray;
                
                if ([[RichDelegate core] updateCreditCardBill:creditCardBill] < 0) {
                    NSLog(@"Update credit card bill failed");
                }
            }
            else {
                /* Load picked transactions/payments in bill */
                creditCardBill.transactions = transPicker.pickedTransArray;
                creditCardBill.payments = paymentPicker.pickedTransArray;
                
                if ([[RichDelegate core] createCreditCardBill:creditCardBill] < 0) {
                    NSLog(@"Create credit card bill failed");
                }
            }
            
            // TODO: if balance of this bill is not 0, add internal transaction with TransactionPropertyInternalCreditCardBalance
            
            /* Clear bill info columns in table */
            creditCardBill = nil;
            transPicker.pickedTransArray = nil;
            paymentPicker.pickedTransArray = nil;
            
            if (self.mode == RichTableModeUpdate)
                [self.navigator popViewControllerAnimated:YES];
            else
                [tableView reloadData];
        }
        else if ([indexPath section] == 2) {
            /* Clear bill info columns in table */
            creditCardBill = nil;
            transPicker.pickedTransArray = nil;
            paymentPicker.pickedTransArray = nil;
            
            NSNumber *billId = [[[[RichDelegate core] creditCardBills] allKeys] objectAtIndex:[indexPath row]];
            RichCreditCardBill *bill = [[[RichDelegate core] creditCardBills] objectForKey:billId];
            
            CreditCardViewController *ccvc = [[CreditCardViewController alloc] init];
            ccvc.title = nil;
            ccvc.mode = RichTableModeUpdate;
            ccvc.creditCardBill = bill;
            ccvc.navigator = self.navigator;
            [self.navigator pushViewController:ccvc animated:YES];
            [ccvc release];
        }
    }
}

#pragma mark - Toolbar button actions

- (void)toolbarDidPressNextButton:(UIBarButtonItem *)sender
{
    if (currentTextfield.tag == 0) {
        /* Account */
        if (accountPicker.account)
            currentTextfield.text = accountPicker.account.name;
    }
    else if (currentTextfield.tag == 1) {
        /* Closing Date */
        currentTextfield.text = [[RichDelegate core] stringFromDate:datePicker.date format:@"yyyy-MM-dd"];
    }
    else if (currentTextfield.tag == 2) {
        /* Due Date */
        currentTextfield.text = [[RichDelegate core] stringFromDate:dueDatePicker.date format:@"yyyy-MM-dd"];
    }
    
    [super toolbarDidPressNextButton:sender];
}

- (void)toolbarDidPressDoneButton:(UIBarButtonItem *)sender
{
    if (currentTextfield.tag == 0) {
        /* Account */
        if (accountPicker.account)
            currentTextfield.text = accountPicker.account.name;
    }
    else if (currentTextfield.tag == 1) {
        /* Closing Date */
        currentTextfield.text = [[RichDelegate core] stringFromDate:datePicker.date format:@"yyyy-MM-dd"];
    }
    else if (currentTextfield.tag == 2) {
        /* Due Date */
        currentTextfield.text = [[RichDelegate core] stringFromDate:dueDatePicker.date format:@"yyyy-MM-dd"];
    }
    
    [super toolbarDidPressDoneButton:sender];
}

#pragma mark - Textfield delegate

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [super textFieldDidBeginEditing:textField];
    
    if (creditCardBill == nil) {
        creditCardBill = [[RichCreditCardBill alloc] init];
    }
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [super textFieldDidEndEditing:textField];
    
    switch (textField.tag) {
        case 0:
            creditCardBill.accountId = accountPicker.account.accountId;
            // TODO: Load/Calculate closing/due date from previous bill of selected account
            [self reloadPickers];
            break;
        case 1:
            creditCardBill.closingDate = datePicker.date;
            [self reloadPickers];
            break;
        case 2:
            creditCardBill.dueDate = dueDatePicker.date;
            break;
        case 3:
        case 4:
            break;
    }
}

#pragma mark - Transaction/Payment picker

- (void)reloadPickers
{
    if (self.mode == RichTableModeUpdate) {
        /* Load picked transactions */
        [[RichDelegate core] creditCardBill:creditCardBill loadAssociatedTransactionsToArray:creditCardBill.transactions database:nil];
        
        transPicker.pickedTransArray = creditCardBill.transactions;
        
        /* Load unassociated transactions */
        NSMutableArray *__unassocTransArray = [[NSMutableArray alloc] init];
        [[RichDelegate core] creditCardBill:creditCardBill loadUnassociatedTransactionsToArray:__unassocTransArray database:nil];
        
        /* Merge transaction array with associated and unassociated transactions */
        NSMutableArray *__allTransArray = [[NSMutableArray alloc] initWithArray:creditCardBill.transactions];
        [__allTransArray addObjectsFromArray:__unassocTransArray];
        
        transPicker.sourceTransArray = __allTransArray;
        
        /* Load picked payments */
        [[RichDelegate core] creditCardBill:creditCardBill loadAssociatedPaymentsToArray:creditCardBill.payments database:nil];
        
        paymentPicker.pickedTransArray = creditCardBill.payments;
        
        /* Load unassociated payments */
        NSMutableArray *__unassocPaymentArray = [[NSMutableArray alloc] init];
        [[RichDelegate core] creditCardBill:creditCardBill loadUnassociatedPaymentsToArray:__unassocPaymentArray database:nil];
        
        /* Merge payment array with associated and unassociated payments  */
        NSMutableArray *__allPaymentArray = [[NSMutableArray alloc] initWithArray:creditCardBill.payments];
        [__allPaymentArray addObjectsFromArray:__unassocPaymentArray];
        
        paymentPicker.sourceTransArray = __allPaymentArray;
    }
    else {
        /* Reload unassociated transactions & payments */
        NSMutableArray *__trans = [[NSMutableArray alloc] init];
        [[RichDelegate core] creditCardBill:creditCardBill loadUnassociatedTransactionsToArray:__trans database:nil];
        transPicker.sourceTransArray = __trans;
        transPicker.pickedTransArray = __trans;
        [__trans removeAllObjects];
        
        [[RichDelegate core] creditCardBill:creditCardBill loadUnassociatedPaymentsToArray:__trans database:nil];
        paymentPicker.sourceTransArray = __trans;
        paymentPicker.pickedTransArray = __trans;
        [__trans removeAllObjects];
        [__trans release];
    }
    
    [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:3 inSection:0],
                                             [NSIndexPath indexPathForRow:4 inSection:0]]
                          withRowAnimation:UITableViewRowAnimationAutomatic];
}

@end
